<?php

namespace App\HttpController\XAppSystem\ZCommon\Admin;


use App\Common\OA\OA;
use App\HttpController\ControllerAdmin;
use App\X\EHelper;
use EasySwoole\Http\Message\UploadFile;
use XWX\Common\H;

class File extends ControllerAdmin
{
    public function uploadImg()
    {
        /** @var UploadFile $file */
        $file = $this->request()->getUploadedFile('file0');
        if ($file == null)
        {
            return $this->funcWriteErr(-8100, '文件不存在');
        }


        $file_type = $file->getClientMediaType();

        $allowed_file_extensions = ["png", "jpg", "gif", "jpeg"];
        $file_extensions = explode('/', $file_type)[1];
        if (!in_array($file_extensions, $allowed_file_extensions))
        {
            return $this->funcWriteErr(-8200, '只能上传指定格式的文件');
        }


        //文件目录
        $ym = H::now()->format('Ym');
        $dir_path = EHelper::funcGetConf('SYS.upload');
        $dir_path = "{$dir_path}/{$ym}/";
        if (!is_dir($dir_path))
        {
            mkdir($dir_path);
        }

        $file_name = H::funcGetOrderID() . '.' . $file_extensions;
        $file_val = "{$ym}/{$file_name}";

        $full_path = $dir_path . $file_name;
        if (!$file->moveTo($full_path))
        {
            return $this->funcWriteErr(-8500, '文件上传失败');
        }


        //http://img.x.siyoumi.com/201910/201910282221245db6f9648a98411176.jpeg
        //201910/201910282221245db6f9648a98411176.jpeg
        $img = [
            'id' => $file_val,
            'url' => OA::funcGetFileUrl($file_val),
        ];
        $this->commonR()->setData('img', $img);


        $this->funcWriteCommonR();
    }
}